package sdklog

import (
	"fmt"
	"io"
	"log"
	"os"
)

var (
	g_writer_debug io.Writer = os.Stdout
	g_writer_info  io.Writer = os.Stdout
	g_writer_error io.Writer = os.Stderr
)

type Logger struct {
	debug *log.Logger
	info  *log.Logger
	err   *log.Logger
	level int
}

func init() {
	LogReopen("z:\\liubenlong\\client_log.txt")
}

func LogReopen(filepath string) {
	out, err := os.Create(filepath)
	if err != nil {
		fmt.Println("open ", filepath, "failed", err)
		return
	}

	g_writer_debug = out
	g_writer_info = out
	g_writer_error = out
}

func LogWriter() io.Writer {
	return g_writer_debug
}

func New(prefix string) *Logger {
	debug := log.New(g_writer_debug, prefix, log.LstdFlags|log.Lshortfile)
	info := log.New(g_writer_info, prefix, log.LstdFlags|log.Lshortfile)
	err := log.New(g_writer_error, prefix, log.LstdFlags)

	return &Logger{debug, info, err, 3}
}

func (l *Logger) SetPrefix(prefix string) {
	l.debug.SetPrefix(prefix)
	l.info.SetPrefix(prefix)
	l.err.SetPrefix(prefix)
}

func (l *Logger) SetOutput(w io.Writer) {
	l.debug.SetOutput(w)
	l.info.SetOutput(w)
	l.err.SetOutput(w)
}

func (l *Logger) Debug(v ...interface{}) {
	if l.level < 3 {
		return
	}
	s := fmt.Sprintf("debug:%s", fmt.Sprint(v...))
	l.debug.Output(2, s)
}

func (l *Logger) Debugf(format string, v ...interface{}) {
	if l.level < 3 {
		return
	}
	s := fmt.Sprintf(format, v)
	l.Debug(s)
}

func (l *Logger) Info(v ...interface{}) {
	if l.level < 2 {
		return
	}
	s := fmt.Sprintf("info:%s", fmt.Sprint(v...))
	l.info.Output(2, s)
}

func (l *Logger) Infof(format string, v ...interface{}) {
	if l.level < 2 {
		return
	}
	s := fmt.Sprintf(format, v)
	l.info.Output(2, s)
}

func (l *Logger) Error(v ...interface{}) {
	if l.level < 1 {
		return
	}
	s := fmt.Sprintf("error:%s", fmt.Sprint(v...))
	l.err.Output(2, s)
}

func (l *Logger) Errorf(format string, v ...interface{}) {
	if l.level < 1 {
		return
	}
	s := fmt.Sprintf(format, v)
	l.err.Output(2, s)
}

func (l *Logger) SetLevel(level int) {
	l.level = level
}
